package com.cti.ftpservice.ws.impl;

import java.util.Arrays;

import javax.xml.namespace.QName;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPFactory;
import javax.xml.soap.SOAPFault;
import javax.xml.ws.WebFault;
import javax.xml.ws.soap.SOAPFaultException;

@WebFault(faultBean = "com.cti.ftpservice.ws.impl.WSFault", targetNamespace = "http://impl.ws.ftpservice.cti.com/", name = "WSException")
public class WSException extends Exception {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private WSFault fault;

	public WSException() {
		super();
		fault = new WSFault();
	}

	public WSException(String message, WSFault fault) {
		super(message);
		this.fault = fault;
	}

	public WSException(String message) {
		super(message);
		this.fault = new WSFault();
	}

	public WSException(WSFault fault) {
		super();
		this.fault = fault;
	}

	public WSException(ErrorModule module, String errorCode) {
		super();
		this.fault = new WSFault(module, errorCode);
	}

	public WSException(ErrorModule module, String errorCode, String arg) {
		this(module, errorCode, new String[] { arg });
	}

	public WSException(ErrorModule module, String errorCode, String[] args) {
		super();
		if (args != null && args.length > 0) {
			this.fault = new WSFault(module, errorCode, Arrays.asList(args));
		} else {
			this.fault = new WSFault(module, errorCode);
		}
	}
	
	@Override
	public synchronized Throwable getCause() {
		SOAPFault soapFault;
		try {
			soapFault=SOAPFactory.newInstance().createFault();
			soapFault.setFaultCode(new QName(String.valueOf(this.getFault().getModule()),this.getFault().getErrorCode()));
			soapFault.setFaultString(this.getFault().toString());
			SOAPFaultException soapFaultException=new SOAPFaultException(soapFault);
			return soapFaultException;
		} catch (SOAPException e) {
			e.printStackTrace();
			return super.getCause();
		}
	}

	public WSFault getFault() {
		return fault;
	}

	public void setFault(WSFault fault) {
		this.fault = fault;
	}
}
